//
//  LXCheckApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/20.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXAgencyFeeApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXAgencyFeeModel.h"
#import "LXChooseCustomViewController.h"
#import "KeHuInfoModel.h"
#import "LXCooperationListViewController.h"
#import "LXCooperationModel.h"
@interface LXAgencyFeeApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;

@property (nonatomic) NSString *customerId;
@property (nonatomic) NSString *payeeId;



@end

@implementation LXAgencyFeeApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
    if (self.type==1) {
        [self layoutCustomNav:self.view title:@"新增中介费"];
    }
    else {
        [self layoutCustomNav:self.view title:@"修改中介费"];
        
    }
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
    
    
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    if (self.type==1) {
        [self setBottomViewWithText:@"确认新增"];
    }
    else {
        [self setBottomViewWithText:@"确认修改"];
    }
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    
    
    // 模型为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.agencyModel)) {
        
        
        
        // 车牌号
        [self.loanDic setValue:self.agencyModel.carNumber forKey:@"carNumber"];
        [self.loanDic setValue:[NSString stringWithFormat:@"%@ %@",self.agencyModel.carBrand,self.agencyModel.carModel] forKey:@"carBrand"];

    
      
        // 修改的时候需要带入数据
        if (self.type==2) {
            
            // 客户
            self.customerId = self.agencyModel.customerId;
            [self.loanDic setValue:self.agencyModel.customerName forKey:@"customerName"];
            // 对方公司
            [self.loanDic setValue:self.agencyModel.payeeName forKey:@"payeeName"];
            self.payeeId = self.agencyModel.payeeId;
            // 应付日期
            [self.loanDic setValue:self.agencyModel.exceptPaidDate forKey:@"exceptPaidDate"];
            // 应付金额
            [self.loanDic setValue:self.agencyModel.amount forKey:@"amount"];

            
            // 备注
            [self.loanDic setValue:self.agencyModel.remark forKey:@"remark"];



        }
        
    }
    
    

    
    self.data = @[
           @{
               @"title":@"车牌号",
               @"key":@"carNumber",
               @"placeHolder" : @"请输入",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":@"品牌型号",
               @"key":@"carBrand",
               @"placeHolder" : @"",
               @"canEdit":@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(1000),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*客户":@"客户",
               @"key":@"customerName",
               @"placeHolder" : @"请选择客户",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"maxLength":@(1000),
               @"sel":self.type==1?@"clickCustomerAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*对方公司":@"对方公司",
               @"key":@"payeeName",
               @"placeHolder" : @"请选择对方公司",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickCompanyAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*应付中介费金额(元)":@"应付中介费金额(元)",
               @"key":@"amount",
               @"placeHolder" : @"请输入金额",
               @"canEdit":self.type==1?@(YES):@(NO),
               @"showAccess":@(NO),
               @"maxLength":@(8),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"inputType":@(NUM_DECIMAL),
               @"sel":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*应付日期":@"应付日期",
               @"key":@"exceptPaidDate",
               @"placeHolder" : @"请选择应付日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"maxLength":@(3),
               @"sel":self.type==1?@"clickDateAction":@"",
               @"height":@(kComHeight)
           },

           @{
               @"title":@"备注",
               @"key":@"remark",
               @"placeHolder" : @"请输入备注...",
               @"height":@(150)
           },
         
           
    ];
    
   
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.row];
    
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.row];


    
    if([dic[@"key"] isEqualToString:@"remark"]){
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = dic[@"placeHolder"];
        cell.textView.maxLength = 200;
        cell.remarkTitle.text = dic[@"title"];
        cell.textView.text = self.loanDic[dic[@"key"]];
        
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            self.loanDic[dic[@"key"]]  = textStr;
        }];
        return cell;
    }
    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    
    
    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    };
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}
#pragma mark -- 选择进厂日期
-(void)clickDateAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"exceptPaidDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择应付日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        [weakSelf.tableView reloadData];
    };
}
// MARK: 选择合作公司
-(void)clickCompanyAction{
    LXCooperationListViewController *vc = [[LXCooperationListViewController alloc] init];
    vc.type = 2;
    [vc setClickVcCallBlock:^(LXCooperationModel * _Nonnull model) {
        
        [self.loanDic setValue:model.name forKey:@"payeeName"];
        self.payeeId = model.ID;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];
}
#pragma mark -- 选择客户
-(void)clickCustomerAction{
    [self.view endEditing:YES];
    LXChooseCustomViewController *vc = [[LXChooseCustomViewController alloc] init];
    [vc setToSendValue:^(KeHuInfoModel * _Nonnull model) {
        [self.loanDic setValue: [NSString stringWithFormat:@"%@",model.customerName]  forKey:@"customerName"];
        self.customerId = model.ID;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];
}

- (NSArray *)data{
    if (!_data) {
        _data = [[NSArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, ScreenHeight - kViewTopHeight - kComHeight - 5) style:UITableViewStylePlain];
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}


#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
    if (StringIsEmpty(self.loanDic[@"customerName"])) {
        showAlert(@"请选择客户");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"payeeName"])) {
        showAlert(@"请选择对方公司");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"amount"])) {
        showAlert(@"请输入应付中介费");
        return;
    }
    if (!StringIsEmpty(self.loanDic[@"amount"])) {
        if ([self.loanDic[@"amount"] intValue] == 0) {
            showAlert(@"应付中介费不能为0元");
            return;
        }
    }
    
    if (StringIsEmpty(self.loanDic[@"exceptPaidDate"])) {
        showAlert(@"请选择应付日期");
        return;
    }
    
    
    
    NSMutableDictionary *dic = @{
        @"carId":self.agencyModel.carId, // 所属车辆id
        @"carNumber":self.agencyModel.carNumber,// 所属车辆车牌号
        @"customerName":self.loanDic[@"customerName"],//客户
        @"customerId":self.customerId,// 客户id
        @"carBrand":self.loanDic[@"carBrand"],// 品牌
        @"carMode":self.loanDic[@"carMode"],// 型号
        @"payeeName":self.loanDic[@"payeeName"],//对方公司
        @"payeeId":self.payeeId,//对方公司id
        @"exceptPaidDate":self.loanDic[@"exceptPaidDate"],// 应付日期
        @"amount":self.loanDic[@"amount"],// 应付金额
        @"remark":self.loanDic[@"remark"],// 备注
        
    }.mutableCopy;
    
    NSString *url;
    if (self.type==1) {
        url = [NSString stringWithFormat:@"%@",POST_PostAddTagencyfeePage];
    }
    else if (self.type==2) {
        url = [NSString stringWithFormat:@"%@",POST_PostUpdateTagencyfeePage];
        [dic setValue:self.agencyModel.ID forKey:@"id"];
    }

    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            if (isSuccess) {
                if (self.type==1) {
                    showAlert(@"新增中介费成功");
                }
                else if (self.type==2) {
                    showAlert(@"修改中介费成功");
                }
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.agencyModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
           
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
   
   
    
    
    
}


@end
